package com.example.routeplansystem.service.impl;


import com.example.routeplansystem.constant.ProcessState;
import com.example.routeplansystem.constant.ResponseStatus;
import com.example.routeplansystem.dao.QuestionDao;
import com.example.routeplansystem.dao.VehicleDao;
import com.example.routeplansystem.entity.dto.ResponseEntity;
import com.example.routeplansystem.entity.po.Question;
import com.example.routeplansystem.entity.po.VehicleMessage;
import com.example.routeplansystem.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.example.routeplansystem.constant.ExceptionMessage.VEHICLE_CANNOT_NULL;
import static com.example.routeplansystem.constant.ExceptionMessage.VEHICLE_NULL_BY_USERID;

@Service
@Slf4j
public class VehicleServiceImpl implements VehicleService {


    @Autowired
    private VehicleDao vehicleDao;

//    @Resource
//    private ApplicationContext applicationContext;

    @Autowired
    private QuestionDao questionDao;

//    @Resource
//    private BatchImportService batchImportService;

//    @Value("${excel.vehicle_check}")
//    private String checkExcelVersion;
//
//    @Value("${excel.vehicle_read}")
//    private String readRuleVersion;

    @Autowired
    private VehicleBatchImportService vehicleBatchImportService;

    @Autowired
    private ResourceLoader resourceLoader;

    //添加车辆信息：
    @Override
    public ResponseEntity<String> vehicleRegister(VehicleMessage vehicleMessage) {
//        checkAlgorithmState(vehicleMessage.getQuestionId());
//        Objects.requireNonNull(vehicleMessage, VEHICLE_CANNOT_NULL);
//        checkAlgorithmState(vehicleMessage.getQuestionId());
        boolean flag = vehicleDao.insertVehicle(vehicleMessage);

        if (!flag){
            return new ResponseEntity<>(ResponseStatus.FAILURE_RESPONSE, "添加车辆信息失败！！！", null);
        } else {
            return new ResponseEntity<>(ResponseStatus.SUCCESS_RESPONSE, "添加车辆信息成功！！！", null);
        }
    }

    private void checkAlgorithmState(int questionId) {
        Question question = questionDao.findQuestionByQuestionId(questionId);
        if (question == null) {
            throw new RuntimeException("没有该Id的问题");
        }
        int processState = question.getProcessState();
        if (processState == ProcessState.PROCESSING_SIMPLE
        || processState == ProcessState.PROCESSING_GENETIC) {
            throw new RuntimeException("算法正在执行，不能添加或者删除基本数据");
        }
        if (processState < ProcessState.LOAD_NODE) {
            throw new RuntimeException("请先导入点");
        }
        if (processState <= ProcessState.LOAD_VEHICLE) {
            questionDao.updateQuestionProcessState(ProcessState.LOAD_VEHICLE, questionId);
        }
    }

    @Override
    public ResponseEntity<List<VehicleMessage>> userVehicleMessage(Integer questionId) {
        List<VehicleMessage> vehicleMessage = vehicleDao.searchVehicleByQuestionId(questionId);
        Objects.requireNonNull(vehicleMessage, VEHICLE_NULL_BY_USERID);

        return new ResponseEntity<>(ResponseStatus.SUCCESS_RESPONSE, "请求成功！！！", vehicleMessage);
    }

    @Override
    public VehicleMessage vehicleMessage(int vehicleId) {
        VehicleMessage vehicleMessage = vehicleDao.searchVehicleByVehicleId(vehicleId);
//        Objects.requireNonNull(vehicleMessage, VEHICLE_NULL_BY_VEHICLEID);
        return vehicleMessage;
    }

    @Override
    public ResponseEntity<String> deleteVehicleBatch(List<Integer> vehicleIdList) {
        boolean flag = vehicleDao.deleteVehicle((ArrayList) vehicleIdList);
        if (!flag){
            return new ResponseEntity<>(ResponseStatus.FAILURE_RESPONSE, "删除车辆信息失败！！！", null);
        } else {
            return new ResponseEntity<>(ResponseStatus.SUCCESS_RESPONSE, "删除车辆信息成功！", null);
        }
    }

    /**
     * 通过Excel上传车辆信息
     * @param mFile
     * @param request
     * @param questionId
     * @return
     */
    @Override
    public ResponseEntity vehicleBatchImport(MultipartFile mFile, HttpServletRequest request, int questionId) {
//       return batchImportService.batchImport(mFile, request, questionId, this::readExcelToDatabase);
        return vehicleBatchImportService.batchImport(mFile,request,questionId);
    }


    @Transactional(rollbackFor = ServerException.class)
    ResponseEntity readExcelToDatabase(Workbook wb, int questionId) {
        checkExcel(wb);
//        VehicelExcelRead excelRead = (VehicelExcelRead) applicationContext.getAutowireCapableBeanFactory()
//                .getBean(this.readRuleVersion);
//        BiTupple<ResponseEntity, List<VehicleMessage>> tupple = excelRead.read(wb, questionId);
//        ResponseEntity responseEntity = tupple.getT();
//        List<VehicleMessage> vehicleMessages = tupple.getU();

//        for (int i = 0; i < vehicleMessages.size(); i++) {
//            boolean insertFlag = vehicleDao.insertVehicle(vehicleMessages.get(i));
//            if (!insertFlag) {
//                responseEntity.setStatus(5);
//                responseEntity.setMsg("服务器错误, 请下次从第" + i+1 + "行数据开始导入" );
//                return responseEntity;
//            }
//        }
//        responseEntity = checkQuestionStateAndUpdate(questionId, responseEntity);
//        return responseEntity;

        return null;
    }

    private ResponseEntity checkQuestionStateAndUpdate(int questionId, ResponseEntity responseEntity) {
        Objects.requireNonNull(responseEntity);
        Question question = questionDao.findQuestionByQuestionId(questionId);
        if (question == null) {
            throw new RuntimeException("没有该ID 的问题");
        }
        int processState = question.getProcessState();
        if (processState < ProcessState.LOAD_NODE) {
            responseEntity.setStatus(6);
            responseEntity.setMsg("请先导入点");
            return responseEntity;
        }
        if (processState <= ProcessState.LOAD_VEHICLE) {
            questionDao.updateQuestionProcessState(ProcessState.LOAD_VEHICLE, questionId);
        }
        return responseEntity;
    }

    private void checkExcel(Workbook workbook) {
//        Objects.requireNonNull(workbook);
//        VehicelExcelCheck excelCheckRule= (VehicelExcelCheck) applicationContext.getAutowireCapableBeanFactory()
//                .getBean(this.checkExcelVersion);
//        excelCheckRule.check(workbook);
    }

    @Override
    public void removeVehicleByQuestionId(int questionId) {
        vehicleDao.deleteVehicleByQuestionId(questionId);
    }

    @Override
    public void removeVehicleByVehicleId(int vehicleId) {
        boolean deleteFlag = vehicleDao.deleteVehicleByVehicleId(vehicleId);
//        ServiceUtil.checkSqlExecuted(deleteFlag);
    }

}
